import datetime
import os

import cv2
import numpy as np
from PIL import Image
from django.shortcuts import render

# Create your views here.
from rest_framework.response import Response
from rest_framework.views import APIView
from tensorflow import keras

from apps.User.CNN import cnn_predict
from apps.User.Unet import unet_predict
from apps.User.core import locate_and_correct
from firepark_admin.models import Plate, Userinfo, use_records, Spaces, all_records
from firepark_park.park import get_fee
from utility.firepark_time import get_datetime_mysql


class Uploadview(APIView):
    def post(self, request, *args, **kwargs):
        print(request.data)
        print(request.headers)
        tokens = request.headers['Token']
        filename = request.FILES["file"].name
        park_id = request.data.get('park_id')
        chepaihaoma = ""
        mingzi = ""
        churuku = ""
        # 判断名字是否存在
        if os.path.exists(os.path.join("media", filename)):
            # 假设文件后缀和文件名以"."区分
            name, suffix = filename.split(".")
            # 存在同名文件处理方法
            name += "1"
            filename = name + "." + suffix
            # mingzi = filename
        with open("media/" + filename, "ab") as f:
            # chunks() 可以指定每次读取的具体大小
            mingzi = filename
            for chunk in request.FILES["file"].chunks():
                f.write(chunk)
        unet = keras.models.load_model('apps/User/unet.h5')
        cnn = keras.models.load_model('apps/User/cnn.h5')
        cnn_predict(cnn, [np.zeros((80, 240, 3))])
        img_src_path = "media/%s" % mingzi
        img_open = Image.open(img_src_path)
        if img_open.size[0] * img_open.size[1] > 240 * 80:
            img_open = img_open.resize((512, 512), Image.ANTIALIAS)
        img_src = cv2.imdecode(np.fromfile(img_src_path, dtype=np.uint8), -1)  # 从中文路径读取时用
        h, w = img_src.shape[0], img_src.shape[1]
        if h * w <= 240 * 80 and 2 <= w / h <= 5:  # 满足该条件说明可能整个图片就是一张车牌,无需定位,直接识别即可
            lic = cv2.resize(img_src, dsize=(240, 80), interpolation=cv2.INTER_AREA)[:, :, :3]  # 直接resize为(240,80)
            img_src_copy, Lic_img = img_src, [lic]
        else:  # 否则就需通过unet对img_src原图预测,得到img_mask,实现车牌定位,然后进行识别
            img_src, img_mask = unet_predict(unet, img_src_path)
            img_src_copy, Lic_img = locate_and_correct(img_src, img_mask)

        Lic_pred = cnn_predict(cnn, Lic_img)  # 利用cnn进行车牌的识别预测,Lic_pred中存的是元祖(车牌图片,识别结果)
        if Lic_pred:
            img = Image.fromarray(img_src_copy[:, :, ::-1])  # img_src_copy[:, :, ::-1]将BGR转为RGB
            # img_Tk = ImageTk.PhotoImage(img)
            # can_src.delete('all')  # 显示前,先清空画板
            # self.can_src.create_image(258, 258, image=self.img_Tk,
            #                           anchor='center')  # img_src_copy上绘制出了定位的车牌轮廓,将其显示在画板上

            # class Spaces(models.Model):
            #     num = models.IntegerField(verbose_name="车位总数量", default=50)
            #     shengyu = models.IntegerField(verbose_name="剩余车位数量", default=50)
            #     park_id = models.IntegerField(verbose_name='停车场id')

            # user = models.ForeignKey("Userinfo", on_delete=models.CASCADE, verbose_name="用户")
            # plate_number = models.CharField(max_length=16, verbose_name="车牌号")
            # sexas = (
            #     ('chu', '出库'),
            #     ('ru', '入库'),
            # )
            # status = models.CharField(choices=sexas, max_length=16, verbose_name="状态")
            # add_time = models.DateTimeField(default=datetime.now, verbose_name="记录时间")
            # park_id = models.IntegerField(verbose_name='停车场id')

            for i, lic_pred in enumerate(Lic_pred):
                print(i, lic_pred[1])
                message = "车牌号是" + lic_pred[1] + "停车场" + str(park_id)
                now_time = get_datetime_mysql()
                if Plate.objects.filter(plate_number=lic_pred[1]).exists():
                    print('有这个车')
                    s = Userinfo.objects.filter(token=tokens).first()
                    counts = use_records.objects.filter(user=s, plate_number=lic_pred[1], park_id=park_id).count()
                    space = Spaces.objects.get(park_id__exact=park_id)
                    if counts % 2 == 0:
                        if space.shengyu <= 0:
                            return Response({"status": 200, "mes": "停车场" + str(park_id) + "没车位了", "info": "入库不了了"})
                        use_records.objects.create(user=s,
                                                   plate_number=lic_pred[1],
                                                   status="ru",
                                                   add_time=now_time,
                                                   park_id=park_id,
                                                   ).save()

                        space.shengyu -= 1
                        space.save()
                        details = "入库"
                    else:
                        ur = use_records.objects.filter(user=s, plate_number=lic_pred[1], park_id=park_id)[0]
                        in_time = str(ur.add_time)
                        in_time = datetime.datetime.strptime(in_time, '%Y-%m-%d %H:%M:%S')
                        fee = get_fee(in_time, now_time, s.vip_status)

                        all_records.objects.create(plate_number=lic_pred[1],
                                                   in_time=ur.add_time,
                                                   out_time=now_time,
                                                   park_id=park_id,
                                                   pay=fee).save()

                        use_records.objects.create(user=s,
                                                   plate_number=lic_pred[1],
                                                   status="chu",
                                                   add_time=now_time,
                                                   park_id=park_id,
                                                   ).save()
                        s.balance -= fee
                        s.save()
                        details = "入库时间：" + str(in_time) + ' 出库时间' + str(now_time) + ' 费用' + str(fee)
                        if s.balance < 5:
                            # 欠费处理
                            details += " 您的余额已不足，请及时续费"

                        space.shengyu += 1
                        space.save()
                else:
                    details = "车库里没有这台车拒绝入库"
                # if i == 0:
                #     self.lic_Tk1 = ImageTk.PhotoImage(Image.fromarray(lic_pred[0][:, :, ::-1]))
                #     self.can_lic1.create_image(5, 5, image=self.lic_Tk1, anchor='nw')
                #     self.can_pred1.create_text(35, 15, text=lic_pred[1], anchor='nw', font=('黑体', 28))
                # elif i == 1:
                #     self.lic_Tk2 = ImageTk.PhotoImage(Image.fromarray(lic_pred[0][:, :, ::-1]))
                #     self.can_lic2.create_image(5, 5, image=self.lic_Tk2, anchor='nw')
                #     self.can_pred2.create_text(40, 15, text=lic_pred[1], anchor='nw', font=('黑体', 28))
                # elif i == 2:
                #     self.lic_Tk3 = ImageTk.PhotoImage(Image.fromarray(lic_pred[0][:, :, ::-1]))
                #     self.can_lic3.create_image(5, 5, image=self.lic_Tk3, anchor='nw')
                #     self.can_pred3.create_text(40, 15, text=lic_pred[1], anchor='nw', font=('黑体', 28))

        else:  # Lic_pred为空说明未能识别
            print("未能识别")
            message = "没有识别成功"
            details = "没识别"
        return Response({"status": 200, "mes": message, "info": details})
